package com.sinping.qh.service.admin.impl;

import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.domain.records.CheckPlan;
import com.sinping.qh.domain.records.CheckRecord;
import com.sinping.qh.domain.records.HiddendangerRecord;
import com.sinping.qh.domain.records.HighLightRecord;
import com.sinping.qh.dto.admin.plan.ApiCheckPlanByAdminDto;
import com.sinping.qh.dto.admin.record.ApiCheckRecordDto;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.query.plan.CheckPlanByAdminQuery;
import com.sinping.qh.repository.mongo.plan.PlanRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.HighLightRepository;
import com.sinping.qh.repository.mongo.records.RecordsRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.ICheckPlanAdminService;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.time.DateFormatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 检查计划实现类
 *
 * @author Tiansx
 * @create 2018-06-01 15:30
 **/
@Service
public class CheckPlanAdminServiceImpl implements ICheckPlanAdminService {
    @Autowired
    private MongoManager mongoManager;
    @Autowired
    private RecordsRepository recordsRepository;
    @Autowired
    private PlanRepository planRepository;
    @Autowired
    private HighLightRepository highLightRepository;
    @Autowired
    private HiddenDangerRecordRepository hiddenDangerRecordRepository;
    @Qualifier("sessionServiceRedisImpl")
    @Autowired
    private ISessionService iSessionService;
    @Override
    public ResDto getPlanList(HttpServletRequest httpRequest, FrontPage page) {
        /**
         * 获取当前用户id
         */
        String token = httpRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {

            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }

        Integer pageSize = page.getSize();
        Integer pageNum = page.getPage();

        Map<String, Object> conditionMap = page.getCondition();

        CheckPlanByAdminQuery checkPlanQuery = new CheckPlanByAdminQuery();
        //设置当前登录用户信息
        checkPlanQuery.setCheckUserId("456d469dc2b74ea2b986bdd892a57b15");
        checkPlanQuery.setCheckUnitId((String) conditionMap.get("check_unit_id"));
        checkPlanQuery.setCheckBuildingId((String) conditionMap.get("check_building_id"));
        try {
            String startDate =(String)conditionMap.get("start_date");
            String endDate = (String)conditionMap.get("end_date");
            if (!StringUtils.isEmpty(startDate)){
                checkPlanQuery.setStartDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, startDate));
            }else {
                checkPlanQuery.setStartDate(null);

            }
            if (!StringUtils.isEmpty(endDate)){
                checkPlanQuery.setEndDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, endDate));
            }else {
                checkPlanQuery.setEndDate(null);

            }
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResDto(Const.PARAM_ERROR,"时间格式不正确");

        }

        String order="DESC";
        if (!StringUtils.isEmpty(page.getOrder())){
            if ("ASC".equals(page.getOrder().toUpperCase())){
                order="ASC";
            }
        }
        String prop = "gmt_created";
        if (!StringUtils.isEmpty(page.getProp())){
            prop=page.getProp();
        }
        //设置查询条件
        Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.fromString(order), prop));
        Page<CheckPlan> pageResult = mongoManager.findPage(checkPlanQuery, pageRequest, CheckPlan.class);
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto,pageResult,ApiCheckPlanByAdminDto.class,page);
        return resDto;
    }

    @Override
    public ResDto getPlanDetail(String id) {

        CheckPlan checkPlan = null;
        if (StringUtils.isNotBlank(id)) {
            checkPlan = planRepository.findOne(id);
            if (checkPlan == null) {
                return new ResDto(Const.SERVER_ERROR, "检查计划不存在");
            }
        }

        ApiCheckPlanByAdminDto apiCheckPlanByAdminDto = BeanMapper.map(checkPlan, ApiCheckPlanByAdminDto.class);
        List<CheckRecord> allByCheckPlanId = recordsRepository.findAllByCheckPlanId(id);

        List<ApiCheckRecordDto> apiCheckRecordDtoList = BeanMapper.mapList(allByCheckPlanId, ApiCheckRecordDto.class);
        //检查计划下所有图片id(前端要求字段)
        List<String> imageIdList=new ArrayList<>();

        for (ApiCheckRecordDto apiCheckRecord : apiCheckRecordDtoList) {
            if (StringUtils.isNotBlank(apiCheckRecord.getId())) {
                /**
                 * 查找亮点记录
                 */
                List<HighLightRecord> highLightRecordList = highLightRepository.findAllByCheckId(apiCheckRecord.getId());
                //检查计划下所有图片id(前端要求字段)/////////////////////////////////////////////////////
                for (HighLightRecord highlightRecord : highLightRecordList) {
                    if (highlightRecord.getUploadImageList()!=null){
                        if (!highlightRecord.getUploadImageList().isEmpty()){
                            for (UploadImage uploadImage:highlightRecord.getUploadImageList()) {
                                if (uploadImage.getId()!=null){
                                    imageIdList.add(uploadImage.getId());
                                }

                            }
                        }

                    }

                }
                 /////////////////////////////////////////////////////
                /**
                 * 查找隐患记录
                 */
                List<HiddendangerRecord> hiddendangerRecordList = hiddenDangerRecordRepository.findAllByCheckId(apiCheckRecord.getId());

                //检查计划下所有图片id(前端要求字段)////////////////////
                for (HiddendangerRecord hiddendangerRecord : hiddendangerRecordList) {
                    if (hiddendangerRecord.getUploadImageList()!=null){
                        if (!hiddendangerRecord.getUploadImageList().isEmpty()){
                            for (UploadImage uploadImage:hiddendangerRecord.getUploadImageList()) {
                                if (uploadImage.getId()!=null){
                                    imageIdList.add(uploadImage.getId());
                                }
                            }
                        }

                    }

                }
                 ///////////////////////////////////////////////////////////////////////

                apiCheckRecord.setHiddendangerRecordList(hiddendangerRecordList);
                apiCheckRecord.setHighLightRecordList(highLightRecordList);

            }

        }

        PageImpl<ApiCheckRecordDto> ApiCheckRecordDtoPage = new PageImpl<>(apiCheckRecordDtoList, new PageRequest(0, apiCheckRecordDtoList.size(), new Sort(Sort.Direction.ASC, "check_status","check_room")), apiCheckRecordDtoList.size());
        List<ApiCheckRecordDto> content = ApiCheckRecordDtoPage.getContent();
        apiCheckPlanByAdminDto.setRecordsList(content);
        apiCheckPlanByAdminDto.setImageIdList(imageIdList);
        String datas = JsonMapper.defaultMapper().toJson(apiCheckPlanByAdminDto);


        return new ResDto(ConstEum.SUCCESS, datas);


    }
}